package com.ruoyi.ruoyiserver.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Stack;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.ruoyiserver.config.IConstants;
import com.ruoyi.ruoyiserver.utils.DatabaseUtils;
import com.ruoyi.ruoyiserver.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.ruoyiserver.mapper.PeBackupMapper;
import com.ruoyi.ruoyiserver.domain.PeBackup;
import com.ruoyi.ruoyiserver.service.IPeBackupService;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-20
 */
@Slf4j
@Service
public class PeBackupServiceImpl implements IPeBackupService {

    private static String backId = null;

    private String filePath = File.separator + "filepath" + File.separator;
    @Value("${spring.datasource.druid.master.url}")
    private String databaseUrl;

    @Value("${spring.datasource.druid.master.username}")
    private String username;

    @Value("${spring.datasource.druid.master.password}")
    private String password;
    @Autowired
    private PeBackupMapper peBackupMapper;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public PeBackup selectPeBackupById(String id) {
        return peBackupMapper.selectPeBackupById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param peBackup 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<PeBackup> selectPeBackupList(PeBackup peBackup) {
        return peBackupMapper.selectPeBackupList(peBackup);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param peBackup 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertPeBackup(PeBackup peBackup) {
        peBackup.setCreateTime(DateUtils.getNowDate());
        return peBackupMapper.insertPeBackup(peBackup);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param peBackup 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updatePeBackup(PeBackup peBackup) {
        return peBackupMapper.updatePeBackup(peBackup);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deletePeBackupByIds(String[] ids) {
        return peBackupMapper.deletePeBackupByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deletePeBackupById(String id) {
        return peBackupMapper.deletePeBackupById(id);
    }

    @Override
    public void beginBackSql(String type) {


        // 开始备份sql
        String id = Utils.getUUID();
        PeBackup backup = new PeBackup();
        Date date = new Date();
        backup.setCreateTime(date);
        backup.setType(type);
        backup.setId(id);
        backup.setCurrent("是");
        String title = Utils.getYYYYdd() + "_" + type;
        String path = exportSqlFile(Utils.getYYYYdd());

        backup.setTitle(title);
        backup.setPath(path);
        log.info("备份的back Id:{}", backup.getId());

        peBackupMapper.insertPeBackup(backup);

    }

    @Override
    public void recover(String id) {
        PeBackup backup = peBackupMapper.selectPeBackupById(id);

        String sqlFile = IConstants.BACK_DIR + backup.getPath();
        if (new File(sqlFile).exists()) {
            String url = databaseUrl.substring(13);
            String host = url.substring(0, url.indexOf(":"));
            String port = url.substring(url.indexOf(":") + 1, url.indexOf("/"));
            String databaseName = url.substring(url.indexOf("/") + 1, url.indexOf("?"));

            backId = id;
            DatabaseUtils databaseUtils = new DatabaseUtils();
            databaseUtils.restore(host, port, username, password, databaseName, sqlFile);
        } else {
            throw new RuntimeException("备份sql脚本文件不存在");
        }
    }

    /**
     * 备份sql
     *
     * @param title 备份sql
     * @return
     */
    private String exportSqlFile(String title) {

        String url = databaseUrl.substring(13);
        String host = url.substring(0, url.indexOf(":"));
        String port = url.substring(url.indexOf(":") + 1, url.indexOf("/"));
        String databaseName = url.substring(url.indexOf("/") + 1, url.indexOf("?"));

        DatabaseUtils databaseUtils = new DatabaseUtils();
        File backDir = new File(IConstants.BACK_DIR);
        if (!backDir.exists()) {
            backDir.mkdirs();
        }

        return databaseUtils.beginBack(host, username, password, port, databaseName, IConstants.BACK_DIR + title + ".sql");
    }

    @Override
    public Boolean getRecoverStatus() {
        if (StringUtils.isBlank(backId)) {
            return Boolean.FALSE;
        }
        // 怎么判断数据库是否恢复成功呢？ 那就判断 peBackUp的 id 这条数据是否存在即可，
        PeBackup backup = this.peBackupMapper.selectPeBackupById(backId);
        if (ObjectUtils.isEmpty(backup)) {
            backId = null;
            return Boolean.FALSE;
        } else {
            // 查到了，就是在备份中！
            return Boolean.TRUE;
        }

    }
}
